package com.example.demo.controller;

import com.example.demo.dto.SalaryDTO;
import com.example.demo.mapper.SalaryMapper;
import com.example.demo.pojo.Salary;
import com.example.demo.util.Result;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

//import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Date;
import java.util.List;

import jakarta.servlet.http.HttpServletResponse;


@CrossOrigin
@RestController
@RequestMapping("/api/salary")
public class SalaryController {

    @Autowired
    private SalaryMapper salaryMapper;
    /**
     * 查询所有薪资信息（含员工姓名、所属部门）
     */
    @GetMapping("/list")
    public Result findAllSalaryWithInfo() {
        List<SalaryDTO> list = salaryMapper.findAllSalaryWithInfo();
        return new Result(200, "查询成功", list);
    }

 /*   // 查询所有薪资
    @GetMapping("/findAll")
    public Result findAll() {
        List<SalaryDTO> list = salaryMapper.findAll();
        return new Result(200, "查询成功", list);
    }*/

    // 根据员工ID查询薪资
    @GetMapping("/findByEmpId")
    public Result findByEmpId(Integer empId) {
        List<SalaryDTO> list = salaryMapper.findByEmpId(empId);
        return new Result(200, "查询成功", list);
    }

    // 新增薪资
    @PostMapping("/save")
    public Result saveSalary(@RequestBody SalaryDTO salaryDTO) {
        // 检查是否已存在该员工该月的薪资记录
        SalaryDTO existingSalary = salaryMapper.findByEmpIdAndMonth(salaryDTO.getEmployeeId(), salaryDTO.getMonth());
        if (existingSalary != null) {
            return new Result(400, "该员工当月薪资记录已存在", null);
        }

        int result = salaryMapper.saveSalary(salaryDTO);
        if (result > 0) {
            return new Result(200, "添加成功", result);
        } else {
            return new Result(400, "添加失败", null);
        }
    }

    // 更新薪资
    @PostMapping("/update")
    @Transactional
    public Result updateSalary(@RequestBody Salary salary) {
        int result = salaryMapper.updateSalary(salary);
       // System.out.println("更新薪资参数：empId=" + salary.getEmpId() + ", month=" + salary.getMonth() + ", money=" + salary.getMoney());
        if (result > 0) {
            return new Result(200, "更新成功", result);
        } else {
            return new Result(400, "更新失败", null);
        }
    }

    // 删除薪资
    @PostMapping("/delete")
    @Transactional
    public Result deleteSalary(@RequestBody Salary salary) {
        // 将LocalDate转换为Date
        Date monthDate = null;
        if (salary.getMonth() != null) {
            monthDate = java.sql.Date.valueOf(salary.getMonth());
        }
        int result = salaryMapper.deleteSalary(salary.getEmpId(), monthDate);
        if (result > 0) {
            return new Result(200, "删除成功", result);
        } else {
            return new Result(400, "删除失败", null);
        }
    }

    // 统计部门薪资总和
    @GetMapping("/sumByDeptId")
    public Result sumSalaryByDeptId(int deptId) {
        BigDecimal sum = salaryMapper.sumSalaryByDeptId(deptId);
        return new Result(200, "查询成功", sum);
    }

    // 统计员工薪资总和
    @GetMapping("/sumByEmpId")
    public Result sumSalaryByEmpId(int empId) {
        BigDecimal sum = salaryMapper.sumSalaryByEmpId(empId);
        return new Result(200, "查询成功", sum);
    }


    // 导出薪资报表
    @GetMapping("/export")
    public void exportSalary(  HttpServletResponse response) throws IOException {
        List<SalaryDTO> list = salaryMapper.findAllSalaryWithInfo();

        // 创建Excel工作簿
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("薪资报表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("薪资ID");
        headerRow.createCell(1).setCellValue("员工姓名");
        headerRow.createCell(2).setCellValue("月份");
        headerRow.createCell(3).setCellValue("薪资");

        // 填充数据
        for (int i = 0; i < list.size(); i++) {
            SalaryDTO salary = list.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(salary.getSalaryId());
            row.createCell(1).setCellValue(salary.getEmployeeName());
            row.createCell(2).setCellValue(salary.getMonth().toString());
            row.createCell(3).setCellValue(salary.getMoney().doubleValue());
        }

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("薪资报表.xls", "UTF-8"));

        // 输出Excel文件
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        workbook.close();
    }
}